<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item>
          <el-button type="primary" @click="handleQuery" v-if="hasAuth(['genealogy:custom-price-discount:query'])">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery" v-if="hasAuth(['genealogy:custom-price-discount:query'])">
            <template #icon><Refresh /></template>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd" v-if="hasAuth(['genealogy:custom-price-discount:add'])">
            <template #icon><Plus /></template>
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
      >
        <el-table-column key="id" label="ID" prop="id" min-width="80" align="center" />
        <el-table-column key="packageId" label="商品ID" prop="packageId" min-width="100" align="center" />
        <el-table-column key="packageId" label="商品名称" prop="packageName" min-width="150" align="center" />
        <el-table-column key="nextAreaCode" label="下级区域代码" prop="nextAreaCode" min-width="120" align="center" />
        <el-table-column key="nextAreaName" label="下级区域名称" prop="nextAreaName" min-width="150" align="center" />
        <el-table-column key="purchasePrice" label="采购价格" prop="purchasePrice" min-width="120" align="center">
          <template #default="scope">
            {{ `¥${scope.row.purchasePrice}` }}
          </template>
        </el-table-column>
        <el-table-column key="createTime" label="创建时间" prop="createTime" min-width="160" align="center" />
        <el-table-column key="updateTime" label="更新时间" prop="updateTime" min-width="160" align="center" />
        <el-table-column fixed="right" label="操作" width="180" v-if="hasAuth(['genealogy:custom-price-discount:edit', 'genealogy:custom-price-discount:delete'])">
          <template #default="scope">
            <el-button type="primary" size="small" link @click="handleEdit(scope.row)" v-if="hasAuth(['genealogy:custom-price-discount:edit'])">编辑</el-button>
            <el-button type="danger" size="small" link @click="handleDelete(scope.row)" v-if="hasAuth(['genealogy:custom-price-discount:delete'])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 价格设置表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="form.id ? '编辑价格设置' : '新增价格设置'" width="500px">
      <el-form ref="formRef" :model="form" label-width="120px" :rules="rules">
        <el-form-item label="商品" prop="packageId">
          <el-select v-model="form.packageId" placeholder="请选择商品" style="width: 100%">
            <el-option
              v-for="pkg in packageOptions"
              :key="pkg.id"
              :label="pkg.packageName"
              :value="pkg.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="采购价格" prop="purchasePrice">
          <el-input-number v-model="form.purchasePrice" :min="0" :precision="2" :step="10" style="width: 100%">
            <template #prefix>¥</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="等级" prop="memberLevelId">
          <el-select v-model="form.memberLevelId" placeholder="请选择下级等级" style="width: 100%" @change="handleMemberLevelChange">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="isFamilyMode ? '下级家族' : '下级区域'" prop="nextAreaCode">
          <el-tree-select
            v-if="!isFamilyMode"
            v-model="form.nextAreaCode"
            placeholder="请选择下级区域"
            :data="regionOptions"
            filterable
            check-strictly
            :render-after-expand="false"
            :props="{
              isLeaf: (data) => isLeafNode(data),
              label: 'name',
              value: 'areaCode',
              children: 'children',
              level: 'level',
              disabled: (data) => !isNodeSelectable(data)
            }"
            :load="loadRegionNodes"
            lazy
            @change="handleAreaChange"
          >
          </el-tree-select>
          <el-select
            v-else
            v-model="form.nextAreaCode"
            placeholder="请选择家族"
            filterable
            style="width: 100%"
            @change="handleAreaChange"
          >
            <el-option
              v-for="item in regionOptions"
              :key="item.id"
              :label="item.familyName || item.name"
              :value="item.id"
            >
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ item.familyName || item.name }}</span>
                <span style="color: #8492a6; font-size: 13px">{{ item.originPlace }}</span>
              </div>
              <div style="font-size: 12px; color: #909399; margin-top: 5px">
                {{ item.mergerName }}
              </div>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="删除确认" width="300px">
      <span>确定要删除该价格折扣吗？</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getPriceSettingPage, getPriceSettingForm, addPriceSetting, updatePriceSetting, deletePriceSetting } from "@/api/price-setting.api";
import PackageAPI from "@/api/genealogy/package.api";
import RegionAPI from "@/api/system/region.api";
import FamilyAPI from "@/api/genealogy/family.api";
import MemberLevelAPI from "@/api/genealogy/member-level.api";
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Plus, Location } from '@element-plus/icons-vue';
import { hasAuth } from "@/plugins/permission";
import { useUserStore } from "@/store";
const { areaCodeBelong, areaCodeScope,baseFlag } = useUserStore().userInfo;
console.log(areaCodeBelong)
// 表格数据
const loading = ref(false);
const total = ref(0);
const pageData = ref([]);
const packageOptions = ref([]);
const regionOptions = ref([]);
const roleOptions = ref([]);
// 是否为家族选择模式
const isFamilyMode = computed(() => areaCodeScope === 5);

// 计算最大级别
const maxLevel = computed(() => {
  // 省级为1，市级为2，县级为3，镇级为4，村级为5
  return baseFlag === 1 ? 5 : areaCodeScope;
});

// 区域选择相关
const treeNodeMap = ref(new Map());

// 查询参数
const queryFormRef = ref();
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 表单相关
const dialogVisible = ref(false);
const formRef = ref();
const form = reactive({
  id: undefined,
  packageId: undefined,
  nextAreaCode: undefined,
  familyId: undefined,
  purchasePrice: 0,
  memberLevelId: undefined
});

// 获取当前选中下级等级的sort值
const currentMemberLevelSort = computed(() => {
  const selectedLevel = roleOptions.value.find(item => item.value === form.memberLevelId);
  return selectedLevel?.sort || 0;
});

// 表单校验规则
const rules = {
  packageId: [{ required: true, message: '请选择商品', trigger: 'change' }],
  nextAreaCode: [{ required: true, message: '请选择下级区域', trigger: 'change' }],
  purchasePrice: [{ required: true, message: '请输入采购价格', trigger: 'blur' }],
  memberLevelId: [{ required: true, message: '请选择下级等级', trigger: 'change' }]
};

// 删除相关
const deleteDialogVisible = ref(false);
const currentDeleteId = ref<number | string>();

// 新增
const handleAdd = () => {
  if (!hasAuth(['genealogy:custom-price-discount:add'])) {
    ElMessage.warning('您没有新增权限');
    return;
  }

  resetForm();
  dialogVisible.value = true;
};

// 编辑
const handleEdit = async (row) => {
  if (!hasAuth(['genealogy:custom-price-discount:edit'])) {
    ElMessage.warning('您没有编辑权限');
    return;
  }

  resetForm();
  try {
    const formData = await getPriceSettingForm(row.id);
    Object.assign(form, formData);
    if(formData.nextLevelId === 1){
      form.memberLevelId = formData.nextLevelId;
    }
    form.memberLevelId = formData.nextLevelId;

    // 确保下级等级选项已加载
    if (roleOptions.value.length === 0) {
      await loadMemberLevelOptions();
    }

    if (isFamilyMode.value) {
      // 如果是家族模式，需要获取家族信息
      if (form.familyId) {
        try {
          // 尝试从缓存中获取家族信息
          const familyData = regionOptions.value.find(item => item.id === form.familyId);
          if (familyData) {
            // 从缓存中找到了家族数据
            form.nextAreaCode = familyData.id; // 设置为下拉框可以正确选中
          } else {
            // 如果缓存中没有，尝试通过API获取
            const family = await FamilyAPI.getFormData(form.familyId);
            if (family) {
              // 将家族ID设置为nextAreaCode，以便下拉框能正确选中
              form.nextAreaCode = family.id;
              // 添加到选项中，如果还不存在
              if (!regionOptions.value.some(item => item.id === family.id)) {
                family.familyName = family.familyName || family.name;
                regionOptions.value.push(family);
              }
            }
          }
        } catch (error) {
          console.error('获取家族信息失败', error);
        }
      }
    } else if (form.nextAreaCode && !treeNodeMap.value.has(form.nextAreaCode)) {
      // 区域模式，尝试从API获取区域信息
      try {
        const regionData = await RegionAPI.getFormDataByCode(form.nextAreaCode);
        if (regionData) {
          treeNodeMap.value.set(form.nextAreaCode, regionData);
        }
      } catch (error) {
        console.error('获取区域信息失败', error);
      }
    }

    dialogVisible.value = true;
  } catch (error) {
    console.error('获取表单数据失败', error);
    ElMessage.error('获取表单数据失败');
  }
};

// 删除
const handleDelete = (row) => {
  if (!hasAuth(['genealogy:custom-price-discount:delete'])) {
    ElMessage.warning('您没有删除权限');
    return;
  }

  currentDeleteId.value = row.id;
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  if (!currentDeleteId.value) return;

  if (!hasAuth(['genealogy:custom-price-discount:delete'])) {
    ElMessage.warning('您没有删除权限');
    return;
  }

  try {
    await deletePriceSetting(currentDeleteId.value);
    ElMessage.success('删除成功');
    handleQuery();
  } catch (error) {
    console.error('删除价格折扣失败', error);
    ElMessage.error('删除价格折扣失败');
  } finally {
    deleteDialogVisible.value = false;
    currentDeleteId.value = undefined;
  }
};

// 重置表单
const resetForm = () => {
  form.id = undefined;
  form.packageId = undefined;
  form.nextAreaCode = undefined;
  form.familyId = undefined;
  form.purchasePrice = 0;
  form.memberLevelId = undefined;
};

// 提交表单
const submitForm = async () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return;
    // 检查权限
    const permissionKey = form.id ? 'genealogy:custom-price-discount:edit' : 'genealogy:custom-price-discount:add';
    if (!hasAuth([permissionKey])) {
      ElMessage.warning(`您没有${form.id ? '编辑' : '新增'}权限`);
      return;
    }
    try {
      // 准备提交的数据
      const submitData = { ...form };
      // 如果是家族模式，将familyId作为单独参数传递
      if (isFamilyMode.value && submitData.familyId) {
        // 使用areaCodeBelong作为nextAreaCode
        submitData.nextAreaCode = areaCodeBelong;
      }
      if (form.id) {
        // 编辑
        await updatePriceSetting(form.id, submitData);
      } else {
        // 新增
        await addPriceSetting(submitData);
      }
      ElMessage.success(form.id ? '编辑成功' : '新增成功');
      dialogVisible.value = false;
      handleQuery();
    } catch (error) {
      console.error(form.id ? '编辑价格设置失败' : '新增价格设置失败', error);
      ElMessage.error(form.id ? '编辑价格设置失败' : '新增价格设置失败');
    }
  });
};

// 判断节点是否可选
const isNodeSelectable = (node) => {
  if (!node) return false;

  // 获取当前选中下级等级
  const selectedLevel = roleOptions.value.find(item => item.value === form.memberLevelId);
  if (!selectedLevel) return false;

  // 如果节点级别等于下级等级的sort值，则可选
  // 如果节点级别小于下级等级的sort值，则可展开但不可选
  // 如果节点级别大于下级等级的sort值，则不可选
  if (node.level < selectedLevel.sort) {
    // 小于当前等级的节点可以展开但不可选
    return false;
  } else if (node.level === selectedLevel.sort) {
    // 等于当前等级的节点可选
    return true;
  } else {
    // 大于当前等级的节点不可选
    return false;
  }
};

// 判断节点是否为叶子节点
const isLeafNode = (data) => {
  if (!data) return false;

  // 获取当前选中下级等级
  const selectedLevel = roleOptions.value.find(item => item.value === form.memberLevelId);
  if (!selectedLevel) return false;

  // 如果节点级别等于下级等级的sort值，则为叶子节点
  return data.level === selectedLevel.sort;
};

// 获取层级名称
const getLevelName = (level) => {
  const levelMap = {
    1: '省',
    2: '市',
    3: '县',
    4: '镇',
    5: '村'
  };
  return levelMap[level] || '未知';
};

const selectedPackage = computed(() => {
  return packageOptions.value.find(pkg => pkg.id === form.packageId);
});

// 加载区域选项
const loadRegionOptions = async () => {
  try {
    // 判断是否为家族选择模式（areaCodeScope === 5）
    if (isFamilyMode.value) {
      // 加载家族列表
      const res = await FamilyAPI.getRegionPage({ pageNum: 1, pageSize: 100 });
      regionOptions.value = res.list || [];

      // 存储家族数据
      regionOptions.value.forEach(item => {
        // 为家族设置相应的属性，保持与区域数据结构一致
        item.level = 5; // 设置为第5级
        item.areaCode = item.id; // 使用id作为areaCode
        item.name = item.familyName; // 使用familyName作为显示名称
        treeNodeMap.value.set(item.id, item);
      });
    } else {
      // 区域选择模式
      // 加载当前用户所属区域的下一级区域
      const currentLevel = areaCodeBelong ? treeNodeMap.value.get(areaCodeBelong)?.level || 0 : 0;
      const nextLevel = currentLevel + 1;

      const data = await RegionAPI.getOptions({ type: nextLevel, areaCode: areaCodeBelong });
      regionOptions.value = data;

      // 存储初始节点数据
      regionOptions.value.forEach(item => {
        // 设置节点的level为下一级
        item.level = nextLevel;
        treeNodeMap.value.set(item.areaCode, item);
      });
    }
  } catch (error) {
    console.error('加载选项失败', error);
  }
};

// 懒加载行政区划节点
const loadRegionNodes = async (node, resolve) => {
  if (node.level === 0) {
    // 根节点，已在初始化时加载省级数据
    return resolve(regionOptions.value);
  }

  // 获取当前选中下级等级
  const selectedLevel = roleOptions.value.find(item => item.value === form.memberLevelId);
  if (!selectedLevel) return resolve([]);

  // 如果当前节点级别已经等于或超过下级等级的sort值，则不再加载子节点
  if (node.level >= selectedLevel.sort) {
    return resolve([]);
  }

  // 使用当前节点的areaCode作为请求参数
  const areaCode = node.data.areaCode;

  try {
    const data = await RegionAPI.getOptions({ areaCode });
    // 存储所有加载的节点数据，用于后续查询
    data.forEach(item => {
      treeNodeMap.value.set(item.areaCode, item);
    });
    resolve(data);
  } catch (error) {
    console.error('加载区域节点失败', error);
    resolve([]);
  }
};

// 处理区域选择变化
const handleAreaChange = (areaCode) => {
  if (!areaCode) return;

  if (isFamilyMode.value) {
    // 家族选择模式
    const selectedFamily = regionOptions.value.find(item => item.id === areaCode);
    if (selectedFamily) {
      form.familyId = areaCode; // 保存家族ID
    }
  } else {
    // 区域选择模式
    // 从映射中获取节点数据
    const selectedNode = treeNodeMap.value.get(areaCode);

    if (selectedNode) {
      form.familyId = undefined; // 清空家族ID
    }
  }
};

// 加载商品选项
const loadPackageOptions = async () => {
  try {
    const res = await PackageAPI.getPage({ pageNum: 1, pageSize: 100 });
    packageOptions.value = res.list || [];
  } catch (error) {
    console.error('加载商品选项失败', error);
  }
};

// 加载下级等级选项
const loadMemberLevelOptions = async () => {
  try {
    const LevelParams = {
      pageNum: 1,
      pageSize: 100,
      memberLevelName: '管理员'
    };
    const data = await MemberLevelAPI.getPage1(LevelParams);
    roleOptions.value = data.list.map(item => ({
      value: item.id,
      sort: item.sort,
      label: item.levelName
    }));
  } catch (error) {
    console.error('加载下级等级选项失败', error);
  }
};

// 处理下级等级变化
const handleMemberLevelChange = (newValue) => {
  if (newValue) {
    const selectedLevel = roleOptions.value.find(item => item.value === newValue);
    if (selectedLevel) {
      // 重置区域选择
      form.nextAreaCode = 0;

      // 清空区域选项并重新加载
      regionOptions.value = [];
      treeNodeMap.value.clear();

      // 重新加载根据下级等级对应的区域级别
      if (selectedLevel.sort <= 5) {
        // 重新加载省级区域
        RegionAPI.getOptions({ areaCode: areaCodeBelong }).then((data) => {
          regionOptions.value = data;
          data.forEach(item => {
            treeNodeMap.value.set(item.areaCode, item);
          });
        });
      }
    }
  } else {
    // 如果清空了下级等级，也清空区域选择
    form.nextAreaCode = 0;
    regionOptions.value = [];
    treeNodeMap.value.clear();
  }
};

// 查询列表
const handleQuery = async () => {
  if (!hasAuth(['genealogy:custom-price-discount:query'])) {
    ElMessage.warning('您没有查询权限');
    return;
  }

  loading.value = true;
  try {
    const res = await getPriceSettingPage(queryParams);
    pageData.value = res.list || [];
    // 处理区域名称显示
    pageData.value.forEach(item => {
      if (item.nextAreaCode && treeNodeMap.value.has(item.nextAreaCode)) {
        item.nextAreaName = treeNodeMap.value.get(item.nextAreaCode).name;
      } else {
        item.nextAreaName = '-';
      }
    });
    // 处理商品名称显示
    pageData.value.forEach(item => {

      const pkg = packageOptions.value.find(pkg => pkg.id == item.packageId);
      console.log(pkg)
      item.packageName = pkg ? pkg.packageName : '-';
    });
    total.value = res.total || 0;
  } catch (error) {
    console.error('查询价格折扣列表失败', error);
    ElMessage.error('查询价格折扣列表失败');
  } finally {
    loading.value = false;
  }
};

// 重置查询
const handleResetQuery = () => {
  if (!hasAuth(['genealogy:custom-price-discount:query'])) {
    ElMessage.warning('您没有查询权限');
    return;
  }

  queryFormRef.value?.resetFields();
  handleQuery();
};
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}
</style>
